package com.itheima.reggie.filter;

/**
 * @author: 爱学Java 不想秃头的 KK
 * @date: 2023/7/25 16:31
 * @version: 1.0
 * @Created with IntelliJ IDEA.
 * @Description:
 */


import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 检查用户是否完成登录
 */
@Slf4j
@Component
@WebFilter(filterName = "checkLoginFilter", urlPatterns = "/*")
public class CheckLoginFilter implements Filter {

    // 路径匹配符，支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        // 1.获取本次请求的URI
        String uri = request.getRequestURI();

        log.info("拦截到请求:{}", uri);

        // 定义不需要拦截的请求路径
        String[] uris = new String[]{
                // 后台登录相关资源
                "/employee/login", // 请求
                "/employee/logout", // 请求
                "/backend/**", // 静态资源
                "/front/**"  // 静态资源
        };

        // 2.判断本次请求是否需要处理
        boolean check = check(uris, uri);

        // 3.如果不需要处理，直接放行
        if (check) {
            log.info("放行的请求:{}", uri);
            chain.doFilter(request, response);
            return;
        }
        // 4.判断登录状态，如果已登录，则直接放行
        if (request.getSession().getAttribute("employee") != null) {
            log.info("用户已登录,用户id为:{}", request.getSession().getAttribute("employee"));
            log.info("当前线程id:{}",Thread.currentThread().getId());
            //在用户登录之后将其id存储到本线程中
            Long empId = (Long) request.getSession().getAttribute("employee");

            BaseContext.setCurrentId(empId);
            chain.doFilter(request, response);
            return;
        }

        log.info("用户未登录!");
        // 如果未登录，通过输出流的方式向客户端响应数据
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
    }

    /**
     * 路径匹配，检查本次请求是否需要放行
     * @param uris
     * @param requestURI
     * @return
     */
    public boolean check(String[] uris, String requestURI) {
        for (String uri : uris) {
            boolean match = PATH_MATCHER.match(uri, requestURI);
            if (match) {
                return true;
            }
        }
        return false;
    }
}
